package com.atguigu.aiproject.service.impl;

import com.atguigu.aiproject.mapper.FollowMapper;
import com.atguigu.aiproject.entity.Follow;
import com.atguigu.aiproject.service.FollowService;
import com.atguigu.aiproject.utils.UserContext;
import com.atguigu.aiproject.vo.FollowCoverVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.List;

import static com.atguigu.aiproject.constant.RedisKeyConstant.USER_FOLLOW_KEY;

@Service
public class FollowServiceImpl  extends ServiceImpl<FollowMapper, Follow> implements FollowService{
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private FollowMapper followMapper;
    /**
     * 关注或取关
     */
    @Override
    public void follow(Integer followUserId, Boolean isFollow) {
        // 1.获取登录用户
        Integer userId = UserContext.getUserId();
        String key = USER_FOLLOW_KEY + userId;
        // 1.判断到底是关注还是取关
        if (isFollow) {
            // 2.关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            boolean isSuccess = save(follow);
            if (isSuccess) {
                // 把关注用户的id，放入redis的set集合 sadd userId followerUserId
                stringRedisTemplate.opsForSet().add(key, followUserId.toString());
            }
        } else {
            // 3.取关，删除 delete from tb_follow where user_id = ? and follow_user_id = ?
            boolean isSuccess = remove(new QueryWrapper<Follow>()
                    .eq("user_id", userId).eq("follow_user_id", followUserId));
            if (isSuccess) {
                // 把关注用户的id从Redis集合中移除
                stringRedisTemplate.opsForSet().remove(key, followUserId.toString());
            }
        }
    }
    /**
     * 判断是否关注
     */
    @Override
    public Boolean isFollow(Integer followUserId) {
        // 1.获取登录用户
        Integer userId = UserContext.getUserId();
        // 2.查询是否关注 select count(*) from tb_follow where user_id = ? and follow_user_id = ?
        Long count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        // 3.判断
        return count > 0;
    }
    /**
     * 查找我的关注或粉丝
     */

    @Override
    public List<FollowCoverVO> findFollowList(String type) {
        // 1.获取登录用户
        Integer userId = UserContext.getUserId();
        if ("follow".equals(type)) {
            // 2.查询关注列表
            return followMapper.findFollowList(userId);
        } else {
            // 3.查询粉丝列表
            return followMapper.findFansList(userId);
        }
    }

}
